<?php

namespace App\Http\Controllers\Backend;

use App\Models\Admin;
use App\Models\Role;
use App\Http\Requests\Backend\AdminRequest;

class AdminController extends BaseController {

    public function index()
    {
        $admins = Admin::ofAll()->paginate($this->pagesize);

        return view('backend.admin.index')->with('admins', $admins);
    }


    public function create()
    {
        $roles = Role::ofAdmins()->get();

        return view('backend.admin.create')->with('roles', $roles);
    }

    public function store(AdminRequest $request)
    {
        $redirect = $request->get('redirect');

        $admin = new Admin();
        $admin->name = $request->get('name');
        $admin->email = $request->get('email');
        $admin->password = bcrypt($request->get('password'));

        $success = $admin->save();

        $roleId = $request->get('roleId');
        if(! empty($roleId))
            $admin->roles()->attach($roleId);

        if($success) {
            return $this->responseCreatedSuccess('管理员添加成功', ['redirect' => $redirect]);
        } else {
            return $this->responseCreatedFail('管理员添加失败');
        }
    }

    public function show($id)
    {
        $admin = Admin::findOrFail($id);
        $roles = Role::ofAdmins()->get();
        
        return view('backend.admin.show')->with('admin', $admin)
                                         ->with('roles', $roles);
    }

    public function update($id, AdminRequest $request)
    {
        $redirect = $request->get('redirect');

        $admin = Admin::findOrFail($id);
        $admin->name  = $request->get('name');;
        $admin->email = $request->get('email');
        $success = $admin->save();

        $roleId = $request->get('roleId');
        $admin->detachRoles();
        $admin->roles()->attach($roleId);

        if ( ! empty($request->password)) {
            $admin->password = bcrypt($request->get('password'));
            $success = $success ? $admin->save() : $success;
        }

        if($success) {
            return $this->responseUpdatedSuccess('管理员修改成功', ['redirect' => $redirect]);
        }else {
            return $this->responseUpdatedFail('管理员修改失败');
        }
    }

    public function destroy($id, AdminRequest $request)
    {
        $redirect = $request->get('redirect');

        $admin = Admin::findOrFail($id);
        $success = $admin->delete();

        if($success) {
            return $this->responseDeletedSuccess('管理员删除成功', ['redirect' => $redirect]);
        }else {
            return $this->responseDeletedFail('管理员删除失败');
        }
    }

}